/**
 * 
 */
package lu.peersoft.timesheet

/**
 * @author thor
 *
 */
public class GoogleCalendar{
    private feedFile = "" 
    private DATA_NAMESPACE = 'http://schemas.google.com/g/2005'
    private QUERY_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss-00:00"
    private feedUrl
    private offset
    private cookie

    GoogleCalendar(config) {
      feedUrl = config.googleCalendar.@feedUrl as String
      cookie = config.googleCalendar.@feedCookie as String
      feedUrl = feedUrl.replaceAll(/\{cookie\}/, cookie)
      offset = Integer.parseInt(config.googleCalendar.@timeOffset as String)
      feedFile = config.googleCalendar.@feedFile as String
    }

    // Must be invoked in the context of TimeCategory and FormatCategory
    def List<Event> getFeed(Date from, Date to) {
      List events = []
      //println new URL("$feedUrl?start-min=${from.format(QUERY_DATE_FORMAT)}&start-max=${to.format(QUERY_DATE_FORMAT)}&orderby=starttime&sortorder=a&max-results=1000").text
      def doc = new XmlSlurper().parse("$feedUrl?start-min=${from.format(QUERY_DATE_FORMAT)}&start-max=${to.format(QUERY_DATE_FORMAT)}&orderby=starttime&sortorder=a&max-results=1000")
      // def doc = new XmlSlurper().parseText(feedFile.text)
      doc.declareNamespace(gd: DATA_NAMESPACE)
      doc.entry.each {
        events.add(new Event(it, offset))
      }
      return events
    }
}
